package com.woniuxy.sys.controller;

public class AlternatePrinting {

    private static int[] array1 = {1,1,1,1};
    private static int[] array2 = {2,2,2,2};

    public static void main(String[] args) {
        Object lock = new Object();

        Thread thread1 = new Thread(() -> printArray(array1, lock));
        Thread thread2 = new Thread(() -> printArray(array2, lock));

        thread1.start();
        thread2.start();
    }

    private static void printArray(int[] array, Object lock) {
        synchronized (lock) {
            for (int value : array) {
                System.out.println(value + " ");
                try {
                    //唤醒等待在该锁上的其他线程
                    lock.notify();
                    //使当前线程进入等待状态，释放锁对象的监视器，并等待其他线程的通知。
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 在循环结束后，再次唤醒等待在该锁上的其他线程
            lock.notify();
        }
    }

}